package com.ai.bitcoin.controller.helper;

import com.ai.bitcoin.bo.PayRequest;
import com.ai.bitcoin.constant.CodeConstant;
import com.ai.bitcoin.constant.CommonConstant;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.jpa.entity.BccOrder;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.util.IdGeneration;
import com.ai.bitcoin.util.IpUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class PayControllerHelper {

    public static PayRequest buildPayRequestData(String symbol, Integer payType, String tradeType, BccUser user, HttpServletRequest req) throws BusinessException {
        if (payType == null) {
            throw new BusinessException(CodeConstant.PARAM_ERROR, "payType is empty");
        }
        if (symbol == null || StringUtils.isBlank(symbol)) {
            throw new BusinessException(CodeConstant.PARAM_ERROR, "symbol is empty");
        }
        String ip = IpUtil.getClientIp(req);
        String orderCode = IdGeneration.getUniqueSign();

        Date now = new Date();
        BccOrder order = new BccOrder();
        order.setOrderCode(orderCode);
        order.setUserSymbol(user.getSymbol());
        order.setPayType(payType);
        order.setSubPackageSymbol(symbol);
        order.setCreateTime(now);
        order.setUpdateTime(now);
        order.setOpenId(user.getOpenId());
        order.setStatus(CommonConstant.UNDONE_PAY);
        order.setType(CommonConstant.ORDER_SUB_PACKAGE_TYPE);
        order.setChildType(CommonConstant.ORDER_SUB_PACKAGE_CHILD_TYPE);

        PayRequest payRequest = new PayRequest(payType, orderCode, user.getSymbol(),ip);
        if (payType == PayRequest.PayType.WEI_XIN_PAY) {
            String openId = user.getOpenId();
            if (openId == null || StringUtils.isBlank(openId)) {
                throw new BusinessException(CodeConstant.PARAM_ERROR, "openId is empty");
            }
            PayRequest.WeiXinPayRequest weiXinPayRequest = new PayRequest.WeiXinPayRequest(openId, tradeType, null);
            payRequest.setWeiXinPayRequest(weiXinPayRequest);
        }
        payRequest.setOrder(order);
        return payRequest;
    }

}
